package com.gdth.http.interceptor;

import java.io.IOException;

import com.gdth.bank.BankApplication;
import com.gdth.bank.model.TAppTokenModel;
import com.gdth.coder.CodeUtil;
import com.gdth.http.listener.ProgressListener;
import com.gdth.http.method.ProgressHelper;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/** 
 * @author  Arvin
 * @version 2016-6-1 3:00:49 
 * 
 */
public class UploadInterceptor implements Interceptor {

	private RequestBody requestBody;
	
	private ProgressListener mProgressListener;
	
	public UploadInterceptor(RequestBody requestBody, ProgressListener mProgressListener) {
		this.requestBody = requestBody;
		this.mProgressListener = mProgressListener;
    }

    @Override 
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request oldRequest = chain.request();
        boolean state = BankApplication.getAppState();
        if (state){
        	BankApplication.setAppState(false);
        	return chain.proceed(oldRequest);
        }
        
        //参数加密
        String token = TAppTokenModel.getCurrentToken();
        String privateKey = TAppTokenModel.getPrivateKey();
        String sPublicKey = TAppTokenModel.getPublicKeyForServer();
        String content = oldRequest.url().queryParameter("content");
        if (content == null || content.equals("")) {
        	content = "content";
        }
        String encodedData = CodeUtil.encryptByPublicForLong(content, sPublicKey);
        String sign = CodeUtil.newSign(encodedData, privateKey);

        // 添加新的参数
        HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                .newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())
                
                .addQueryParameter("sign", sign)
                .addQueryParameter("token", token)
                .setQueryParameter("content", encodedData);

        // 新的请求
//        Request newRequest = oldRequest.newBuilder()
//                .method(oldRequest.method(), oldRequest.body())
//                .url(authorizedUrlBuilder.build())
//                .header("User-Agent", "OkHttp Headers.java")
////		        .addHeader("Accept", "application/json; q=0.5")
////		        .addHeader("Accept", "application/vnd.github.v3+json")
//                .build();

      //进行包装，使其支持进度回调
        final Request request = oldRequest.newBuilder()
        		.url(authorizedUrlBuilder.build())
        		.post(ProgressHelper.addProgressRequestListener(requestBody, mProgressListener))
        		.build();
        
        return chain.proceed(request);
    }
}
